<template>
  <div class="card content-box">
    <div class="table-box">
      <ProTable ref="proTable" :columns="columns" :request-api="getTableList">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button v-auth="'file:file_detail:upload'" type="primary" :icon="CirclePlus" @click="onSave">上传</el-button>
          <el-button
            v-auth="'file:file_detail:delete'"
            type="danger"
            :icon="Delete"
            plain
            :disabled="!scope.isSelected"
            @click="batchDelete(scope.selectedListIds)"
          >
            批量删除
          </el-button>
          <el-button v-auth="'file:file_detail:export'" type="primary" :icon="Download" plain @click="exportExcel">
            导出
          </el-button>
        </template>
        <template #originalFilename="scope">
          <el-button type="primary" @click="onPreview(scope.row, false)" link>{{ scope.row.originalFilename }}</el-button>
        </template>
        <template #size="scope">
          <span>{{ getFileSize(scope.row.size) }}</span>
        </template>
        <template #thUrl="scope">
          <el-button v-if="scope.row.thFilename" type="primary" @click="onPreview(scope.row, true)" link>
            {{ scope.row.thFilename }}
          </el-button>
          <span v-else>--</span>
        </template>
        <!-- 菜单操作 -->
        <template #operation="scope">
          <el-button v-auth="'file:file_detail:download'" type="primary" link :icon="Download" @click="onDownload(scope.row)">
            下载
          </el-button>
          <el-button v-auth="'file:file_detail:delete'" type="danger" link :icon="Delete" @click="onDelete(scope.row)">
            删除
          </el-button>
        </template>
      </ProTable>
      <FileDetailOperateDrawer ref="drawerRef"></FileDetailOperateDrawer>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { CirclePlus, Delete, Download } from "@element-plus/icons-vue";
import {
  deleteFileDetail,
  downloadFile,
  exportFileDetailExcel,
  FileDetailPageResult,
  getFileDetailPage,
  getPlatformInfo
} from "@/api/modules/file/FileDetail";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { ref } from "vue";
import FileDetailOperateDrawer from "@/views/file/fileDetail/FileDetailOperateDrawer.vue";
import { useUserStore } from "@/stores/modules/user";
import { getEnumDictItem } from "@/api/modules/sys/dict";

// 表格配置项
const columns: ColumnProps[] = [
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "platform",
    label: "存储平台",
    enum: () => getPlatformInfo(),
    fieldNames: { label: "platform", value: "platform" },
    tag: true
  },
  {
    prop: "originalFilename",
    label: "原始文件名",
    search: { el: "input", tooltip: "原始文件名" }
  },
  {
    prop: "size",
    label: "文件大小"
  },
  {
    prop: "thUrl",
    label: "缩略图访问路径",
    width: 300
  },
  {
    prop: "uploadStatus",
    label: "上传状态",
    enum: () => getEnumDictItem("UploadStatus")
  },
  {
    prop: "createTime",
    label: "创建时间"
  },
  { prop: "operation", label: "操作", fixed: "right" }
];

const proTable = ref<ProTableInstance>();

const getTableList = param => {
  return getFileDetailPage(param);
};

/**
 * 获取文件大小(带后缀)
 * @param size 文件原始大小(字节单位)
 */
const getFileSize = size => {
  if (!size) {
    return "未知大小";
  }
  if (size < Math.pow(1024, 1)) {
    return computeByte(size, 0) + " b";
  }
  if (size < Math.pow(1024, 2)) {
    return computeByte(size, 1) + " KB";
  }
  if (size < Math.pow(1024, 3)) {
    return computeByte(size, 2) + " MB";
  }
  if (size < Math.pow(1024, 4)) {
    return computeByte(size, 3) + " GB";
  }
  if (size < Math.pow(1024, 5)) {
    return computeByte(size, 4) + " TB";
  }
  return "文件过大";
};

/**
 * 计算字节大小
 * @param size 字节
 * @param unit 转换单位
 */
const computeByte = (size: number, unit: number) => {
  return Math.round((size / Math.pow(1024, unit)) * 100) / 100;
};

const drawerRef = ref<InstanceType<typeof FileDetailOperateDrawer> | null>(null);

const onSave = () => {
  drawerRef.value?.openDrawer({
    getTableList: proTable.value?.getTableList,
    enumMap: proTable.value?.enumMap
  });
};

const onDownload = async (row: FileDetailPageResult) => {
  useDownload(downloadFile, row.id);
};

// 删除信息
const onDelete = async (row: FileDetailPageResult) => {
  await useHandleData(deleteFileDetail, [row.id], `删除【${row.originalFilename}】`);
  proTable.value?.getTableList();
};

// 批量删除
const batchDelete = async (ids: string[]) => {
  await useHandleData(deleteFileDetail, ids, "删除所选信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 导出
const exportExcel = async () => {
  useDownload(exportFileDetailExcel, proTable.value?.searchParam);
};

const userStore = useUserStore();

// 预览
const onPreview = async (row: FileDetailPageResult, thumbnail: boolean) => {
  let url = thumbnail ? row.thUrl : row.url;
  if (row.platform === "local") {
    // 本地预览的话,需要携带token
    url += "?" + userStore.tokenName + "=" + userStore.token;
  }
  // 重新打开窗口
  window.open(url, "_blank");
};
</script>
